﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kevin.Shop.Business.Core.Components;
using Kevin.Shop.Business.Products.Components;
using Kevin.Shop.Business.Service.Entity.Helper;
using RiderShop.Mobile.Common.Component;
using RiderShop.Mobile.ServiceEntity.Product;
using Kevin.Shop.Business.Core.Components.Responser;
using Kevin.Shop.Business.Service.Entity.SalesManagement.GiftCard;
using Kevin.Shop.Business.Service.Entity.SalesManagement.Enumerations;
using RiderShop.Mobile.ServiceEntity.Store;
using Kevin.Shop.Business.Service.Entity.SalesManagement.PromotionCode;
using RiderShop.Mobile.Common.ThirdEntity;
using Senparc.Weixin.Helpers;
using System.Security.Cryptography;
using System.Configuration;

namespace RiderShop.Mobile.Modle.MyAccount
{
    public class MyPromotionCodeModel
    {
        #region Method
        /// <summary>
        /// 得到用户的优惠券列表
        /// </summary>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="status">状态 0未过期|1已使用|2已过期</param>
        /// <param name="promotionType">优惠类型 0 代金券|1 红包</param>
        /// <returns>优惠券列表</returns>
        public void GetUserPromotionCodes(int pageIndex, int pageSize, int status, int promotionType)
        {
            string url = SiteUrl.FormatUrl("SalesManagement_GetPrmotionCodeList");
            var query = new PromotionCodeQuery()
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                UserID = WebClientContext.Current.UserId,
                Status = status,
                PromotionType = promotionType
            };
            var result = RestfulHelper.Query<PromotionCodeCustomerEntity>(url, query);
            Status = status;
            PromotionType = promotionType;
            if (result != null)
            {
                if (!string.IsNullOrEmpty(result.Tag))
                {
                    var list = result.Tag.Split(',');
                    NoUsePromotionCodeTotalCount = list.Length == 3 ? Convert.ToInt32(list[0]) : 0;//未使用优惠券数
                    NoUsePromotionCodeTotalPage = (int)Math.Ceiling(NoUsePromotionCodeTotalCount / (double)pageSize);//未使用优惠券页数
                    UsedPromotionCodeTotalCount = list.Length == 3 ? Convert.ToInt32(list[1]) : 0;//已使用优惠券数
                    UsedPromotionCodeTotalPage = (int)Math.Ceiling(UsedPromotionCodeTotalCount / (double)pageSize);//已使用优惠券页数
                    ExpirePromotionCodeTotalCount = list.Length == 3 ? Convert.ToInt32(list[2]) : 0;//已过期优惠券数
                    ExpirePromotionCodeTotalPage = (int)Math.Ceiling(ExpirePromotionCodeTotalCount / (double)pageSize);//已过期优惠券页数
                }
                PromotionCodeList = result.Data;
                TotalCount = result.TotalRecords;
            }
        }

        /// <summary>
        /// 得到用户通过参与游戏领取的优惠券
        /// </summary>
        /// <param name="orderNumber">orderNumber</param>
        /// <returns>优惠券</returns>
        public void GetUserPromotionCodeByOrderNumber(string orderNumber)
        {
            string url = SiteUrl.FormatUrl("SalesManagement_GetPrmotionCodeList");
            var query = new PromotionCodeQuery()
            {
                OrderNumber = orderNumber,
                UserID = WebClientContext.Current.UserId,
                Status = -1,
                PromotionType = -1
            };
            var result = RestfulHelper.Query<PromotionCodeCustomerEntity>(url, query);
        
            if (result != null)
            {                
                PromotionCodeList = result.Data;
            }
        }

        /// <summary>
        /// 通过PrmotionCode得到Prmotion信息和其下的item信息
        /// </summary>
        /// <param name="promotionCode"></param>
        /// <returns></returns>
        public void GetPromotionCodeAndPromotionItems(string promotionCode)
        {
            string url = SiteUrl.FormatUrl("SalesManagement_GetPromotionCodeAndPromotionItems", promotionCode);
            PromotionCodeEntity result = RestfulHelper.QueryWithSingle<PromotionCodeEntity>(url);

            PromotionCodeInfo = result;
        }

        public void GetUserSharedPrmotionCodes(int pageIndex, int pageSize, string promotionCode, string friendUserName)
        {
            string url = SiteUrl.FormatUrl("SalesManagement_GetUserSharedPrmotionCodeList");
            var query = new PromotionCodeQuery()
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                PromotionCode = promotionCode,
                FriendUserName = friendUserName
            };
            var result = RestfulHelper.Query<PromotionCodeCustomerEntity>(url, query);
            if (result != null)
            {
                PromotionCodeList = result.Data;
                TotalCount = result.TotalRecords;
            }
        }

        /// <summary>
        /// 领取优惠券
        /// </summary>
        /// <param name="promotionCode">优惠券</param>
        /// <returns>status = true 领取成功|false 领取失败 ErrorMessage 错误描述</returns>
        public ServiceResponser ReceivePrmotionCode(string promotionCode, string orderNumber)
        {
            var request = new PromotionCodeRequest()
            {
                PromotionCode = promotionCode,
                OrderNumber = orderNumber,
                UserId = WebClientContext.Current.UserId,
            };
            string url = SiteUrl.FormatUrl("SalesManagement_ReceivePrmotionCode");
            var result = RestfulHelper.Update(url, request);

            return result;
        }

        /// <summary>
        /// 领取优惠券
        /// </summary>
        /// <param name="promotionCode">优惠券</param>
        /// <returns>status = true 领取成功|false 领取失败 ErrorMessage 错误描述</returns>
        public ServiceResponser ReceiveUserShardPrmotionCode(string promotionCode, string friendUserName, string thirdUserId, string thirdUserHeader, string thirdUserName)
        {
            var request = new PromotionCodeRequest()
            {
                PromotionCode = promotionCode,
                FriendUserName = friendUserName,
                ThirdUserId = thirdUserId,
                ThirdUserHeader = thirdUserHeader,
                ThirdUserName = thirdUserName
            };
            string url = SiteUrl.FormatUrl("SalesManagement_ReceivePrmotionCode");
            var result = RestfulHelper.Update(url, request);

            return result;
        }

        /// <summary>
        /// 根据卡券得到时间戳和签名
        /// </summary>
        /// <param name="cardId">卡券id</param>
        public void GetTimeStampAndSignature(string cardId)
        {
            string appSecret = ConfigurationManager.AppSettings["WeixingAuthAppSecret"];
            CardId = cardId;
            TimeStamp = DateTimeHelper.GetWeixinDateTime(DateTime.Now);
            Signature = GetSignature(appSecret, cardId, TimeStamp.ToString());
        }

        #region 计算签名
        /// <summary>
        /// 算签名
        /// </summary>
        /// <param name="appsecret">应用密钥</param>
        /// <param name="card_id">卡券编号</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="balance">红包余额，以分为单位</param>
        /// <returns></returns>
        public string GetSignature(string appsecret, string card_id, string timestamp, string balance = "")
        {
            string[] strArray = (from z in new string[] { appsecret, card_id, timestamp, balance }
                                 orderby z
                                 select z).ToArray<string>();
            string s = string.Join("", strArray);
            byte[] buffer = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(s));
            StringBuilder builder = new StringBuilder();
            foreach (byte num in buffer)
            {
                builder.AppendFormat("{0:x2}", num);
            }

            return builder.ToString();
        }

        /// <summary>
        /// 算签名
        /// </summary>
        /// <param name="appsecret">应用密钥</param>
        /// <param name="card_id">卡券编号</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="code"></param>
        /// <param name="openid"></param>
        /// <param name="balance">红包余额，以分为单位</param>
        /// <returns></returns>
        public string GetSignature(string appsecret, string card_id, string timestamp, string code, string openid, string balance = "")
        {
            string[] strArray = (from z in new string[] { appsecret, card_id, timestamp, code, openid, balance }
                                 orderby z
                                 select z).ToArray<string>();
            string s = string.Join("", strArray);
            byte[] buffer = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(s));
            StringBuilder builder = new StringBuilder();
            foreach (byte num in buffer)
            {
                builder.AppendFormat("{0:x2}", num);
            }

            return builder.ToString();
        }
        #endregion
        #endregion

        #region Property
        public string Message
        {
            get;
            set;
        }

        public int Status
        {
            get;
            set;
        }
        
        public int TotalCount
        {
            get;
            set;
        }

        public int PromotionType
        {
            get;
            set;
        }

        /// <summary>
        /// 用户的优惠券列表
        /// </summary>
        public List<PromotionCodeCustomerEntity> PromotionCodeList { get; set; }

        /// <summary>
        /// 优惠券信息(PrmotionCode得到Prmotion信息和其下的item信息)
        /// </summary>
        public PromotionCodeEntity PromotionCodeInfo { get; set; }

        //未使用的优惠券总数
        public int NoUsePromotionCodeTotalCount
        {
            get;
            set;
        }

        //未使用优惠券总页数
        public int NoUsePromotionCodeTotalPage
        {
            get;
            set;
        }

        //已使用的优惠券总数
        public int UsedPromotionCodeTotalCount
        {
            get;
            set;
        }

        //已使用优惠券总页数
        public int UsedPromotionCodeTotalPage
        {
            get;
            set;
        }

        //过期的优惠券总数
        public int ExpirePromotionCodeTotalCount
        {
            get;
            set;
        }

        //已过期优惠券总页数
        public int ExpirePromotionCodeTotalPage
        {
            get;
            set;
        }

        /// <summary>
        /// 卡券编号
        /// </summary>
        public string CardId { get; set; }

        /// <summary>
        /// 时间戳
        /// </summary>
        public long TimeStamp { get; set; }

        /// <summary>
        /// 签名
        /// </summary>
        public string Signature { get; set; }
        #endregion
    }
}
